package cn.edu.zstu.qingzhu.qingzhushop.controller;

import cn.edu.zstu.qingzhu.qingzhushop.entity.RegisterDTO;
import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.entity.User;
import cn.edu.zstu.qingzhu.qingzhushop.entity.UserModifyPasswordDTO;
import cn.edu.zstu.qingzhu.qingzhushop.exception.RegisterException;
import cn.edu.zstu.qingzhu.qingzhushop.provider.UCloudProvider;
import cn.edu.zstu.qingzhu.qingzhushop.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-10-17 18:41
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController extends BaseRestController<IUserService,User,Integer>{
    @Autowired
    IUserService iUserService;
    @Autowired
    UCloudProvider uCloudProvider;

    /**
     *
     * @param phone
     * @param password
     * @return
     */
    @ApiOperation(value = "用户登陆",notes = "用户登陆",response = Object.class)
    @RequestMapping(value = "/login",method = { RequestMethod.POST})
    public ResponseBean login(@RequestParam String phone, @RequestParam String password){
        List<User> users = iUserService.selectByUserPhone(phone);
        if (users == null || users.size() ==0) {
            return ResponseBean.error("该用户不存在");
        } else {
            User user = users.get(0);
            BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();

            if (bcryptPasswordEncoder.matches(password,user.getPassword())) {
                // 如果密码与邮箱配对成功:
                return ResponseBean.success(user);
            } else {
                // 如果密码与邮箱不匹配:
                return ResponseBean.error("账号密码错误");
            }
        }
    }
    public Object login(Authentication authentication){
        if(authentication==null){
            return "index";
        }else {
            return "redirect:/";
        }

    }

    /**
     *
     * @param registerDTO
     * @return
     */
    @ApiOperation(value = "用户注册",notes = "用户注册",response = Object.class)
    @RequestMapping(value ="/register",method = { RequestMethod.POST})
    public ResponseBean register(@RequestBody RegisterDTO registerDTO) {
        if (StringUtils.isEmpty(registerDTO.getPassword()) || StringUtils.isEmpty(registerDTO.getPhone())) {
            return new ResponseBean.Builder()
                    .setStatus(400)
                    .setMsg("必填项未填！")
                    .setData(null)
                    .build();
        }
        User user;
        try{
            user = iUserService.registerUser(registerDTO.getPhone(),registerDTO.getPassword());
        }catch (RegisterException ex){
            return new ResponseBean.Builder()
                    .setStatus(400)
                    .setMsg(ex.getMessage())
                    .setData(null)
                    .build();
        }
        return ResponseBean.success(user);
    }

    /**
     *
     * @param authentication
     * @return
     */
    @ApiOperation(value = "退出",notes = "退出",response = Object.class)
    @RequestMapping(value = "/logout",method = { RequestMethod.POST})
    public Object logout(Authentication authentication){
        authentication.setAuthenticated(false);
        if(authentication==null){
            return "index";
        }else {
            return "redirect:/";
        }

    }

    /**
     *
     * @param modifyDTO
     * @return
     */
    @ApiOperation(value = "修改用户密码",notes = "修改用户密码",response = Object.class)
    @RequestMapping(value = "/modifyPwd",method = {RequestMethod.POST})
    public ResponseBean modifyPwd(@RequestBody UserModifyPasswordDTO modifyDTO){
        if(!modifyDTO.getNewPassword().equals(modifyDTO.getConfirmNewPassword())){
            if(!StringUtils.isEmpty(modifyDTO.getConfirmNewPassword())){
                return new ResponseBean.Builder()
                        .setStatus(400)
                        .setMsg("两次密码输入不一致")
                        .setData(null).build();
            }
        }
        if (iUserService.modifyPassword(modifyDTO.getPhone(),modifyDTO.getOldPassword(),modifyDTO.getNewPassword())) {
            return ResponseBean.success();
        }else{
            return ResponseBean.error();
        }
    }

    /**
     *
     * @return
     */
    @ApiOperation(value = "获取所有用户",notes = "获取所有用户",response = Object.class)
    @RequestMapping(value = "/list",method = {RequestMethod.GET})
    public Object getAllUser(){
        return iUserService.list();
    }

    /**
     * 分页用户
     * @return
     */
    @ApiOperation(value = "用户信息分页查询",notes = "查询用户",response = Object.class)
    @ResponseBody
    @RequestMapping(value = "/",method = {RequestMethod.GET})
    public Object getUserByPage(@ApiParam(name = "page",value = "页数") @RequestParam(defaultValue = "1") Integer page,
                                @ApiParam(name = "size",value = "记录数")@RequestParam(defaultValue = "10") Integer size,
                                @ApiParam(name = "user",value = "用户实体")User user,
                                @ApiParam(name = "firstTime",value = "注册日期区间") Date[] firstTime,
                                @ApiParam(name = "lastTime",value = "最后登录日期区间")Date[] lastTime){
        if(user==null){
            user = new User();
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("","");
        //System.out.println(firstTime[0]);
        if(firstTime!=null){
            queryWrapper.between("first_time",new Timestamp(firstTime[0].getTime()),
                    new Timestamp(firstTime[1].getTime()));
        }
        if(lastTime!=null){
            queryWrapper.between("last_time",new Timestamp(lastTime[0].getTime()),
                    new Timestamp(lastTime[1].getTime()));
        }

        return iUserService.page(new Page<>(page,size), queryWrapper);
    }

    /**
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "用户头像上传",notes = "用户头像上传",consumes = "multipart/form-data",response = Object.class)
    @RequestMapping(value = "/avatar/upload",method = {RequestMethod.POST}, headers = "content-type=multipart/form-data")
    public Object avatarUpload(@ApiParam(value = "头像文件",type = "file",required = true)
                               @RequestParam("avatar") MultipartFile file){
        if(file.isEmpty()){
            return ResponseBean.error("无文件");
        }

        String fileName = UUID.randomUUID()+file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);
        try {
            String url=uCloudProvider.putStream(file.getInputStream(),file.getContentType(),fileName);
            return ResponseBean.ok("上传成功",url);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResponseBean.error("上传错误");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ResponseBean.error("上传错误");
        }

    }

    @ApiOperation(value = "用户总数")
    @GetMapping("/total")
    public ResponseBean getUserTotal(){
        return ResponseBean.ok("",iUserService.count());
    }

    /**
     * 用户禁用与解除禁用(0-未锁定 1-已锁定)
     */
    @RequestMapping(value = "/lock/{id}", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean lock(@PathVariable Integer id,@RequestBody Integer lockStatus) {
        if (id < 1) {
            return ResponseBean.error("参数异常！");
        }
        if (lockStatus != 0 && lockStatus != 1) {
            return ResponseBean.error("操作非法！");
        }
        if (iUserService.lockUser(id, lockStatus)) {
            return ResponseBean.success();
        } else {
            return ResponseBean.error("禁用失败");
        }
    }

    /**
     *
     * @return
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportData() {
        List<User> list = iUserService.list();
        // (List<Employee>) employeeService.getEmployeeByPage(null, null, new Employee(),null).getData();
        //return POIUtils.employee2Excel(list);
        ResponseBean.ok("导出成功",list);
        return null;
    }

    /**
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public Object importData(MultipartFile file) throws IOException {
        List<User> list = null;
        // POIUtils.excel2Employee(file, nationService.getAllNations(), politicsstatusService.getAllPoliticsstatus(), departmentService.getAllDepartmentsWithOutChildren(), positionService.getAllPositions(), jobLevelService.getAllJobLevels());
        if (iUserService.saveOrUpdateBatch(list)) {
            return ResponseBean.ok("上传成功");
        }
        return ResponseBean.error("上传失败");
    }
}
